<?php
require_once 'Zend/Loader.php';

/**
 * DataConnection class
 *
 * @author Eugene Zabolotniy
 */
final class Service_DataConnection
{
    /**
     * @var Zend_Config
     */
    private static $_config = null;
    private static $_connections = array();

    public static function init($config)
    {
        if (is_string($config)) {
            require_once 'Zend/Config/Xml.php';
            $config = new Zend_Config_Xml($config);
        }

        if ($config instanceof Zend_Config) {
            self::$_config = $config;
        } else {
            require_once 'Service/DataConnection/Exception.php';
            throw new Service_DataConnection_Exception('Wrong data connections config.');
        }
    }

    public static function getConnection($name)
    {
        if (!isset(self::$_connections[$name])) {
            $config = self::_getSettings($name);
            if ($config && $config->className) {
                Zend_Loader::loadClass($config->className);
                self::$_connections[$name] = new $config->className($config->options->toArray(), $name);
            } else {
                require_once 'Service/DataConnection/Exception.php';
                throw new Service_DataConnection_Exception('Wrong connection name.');
            }
        }

        return self::$_connections[$name];
    }

    private static function _getSettings($name)
    {
        if (self::$_config && isset(self::$_config->{$name})) {
            return self::$_config->{$name};
        }
        return null;
    }
}
